<?php

namespace App;

use Encore\Admin\Traits\DefaultDatetimeFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * @property  string $name
 * @property string $access_id
 * @property string $access_key
 */
class OssConfig extends Model
{
    use DefaultDatetimeFormat;

    protected $fillable = [
        'name',
        'access_id',
        'access_key',
        'bucket',
        'endpoint',
        'endpoint_internal',
        'enabled',
        'prefix',
        'sts',
        'ssl',
        'isCName',
        'debug',
        'cdnDomain'
    ];

    protected $casts = [
        'sts' => 'json'
    ];

    public static function foreverOssConfig()
    {
        $model = self::query()->where('enabled', 1)->orderByDesc('updated_at')->first();
        if ($model instanceof self) {
            $data = $model->only([
                'access_id',
                'access_key',
                'bucket',
                'endpoint',
                'endpoint_internal',
                'prefix',
                'sts',
                'ssl',
                'isCName',
                'debug',
                'cdnDomain'
            ]);
            Cache::forever('storage_ali_oss_default', $data);
        } else {
            Cache::forget('storage_ali_oss_default');
        }
    }
}
